<template>
  <div class="w-full h-full">
    <Stem :data="stem" />
    <Recorder ref="recorderRef" @error="handlerRecorderError" />
  </div>
</template>

<script>
import Stem from '@/components/question/stem/index'
import { mapState } from 'vuex'
import { generateStudentAnswer, formatQuestionStem } from '@/utils/question'
import Recorder from '@/components/recorder'
import { uploadFile } from '@/api/common'

export default {
  components: { Stem, Recorder },
  inject: ['globalData'],
  data() {
    return {}
  },
  computed: {
    stageIndex() {
      const { stageIndex } = this.globalData.controller

      return stageIndex
    },
    ...mapState(['homework']),
    currentHomework() {
      return this.homework.currentHomework
    },
    currentQuestion() {
      const { questions, questionIndex } = this.currentHomework

      return questions[questionIndex]
    },
    stem() {
      const { stem } = this.currentQuestion

      const {
        info: { image = '', analyze = '' }
      } = stem

      return formatQuestionStem({
        html: `<div><span style="font-size:0.26rem;font-weight:500">听后转述信息</span><p><span>请再听一遍短文，完成转述。</span></p><p>${analyze}</><p><img src="${image}" /></p></div>`,
        og: null,
        sqs: [],
        type: '英语听说-听后转述'
      })
    }
  },
  created() {
    this.$on('pause', () => {})
    this.$on('resume', () => {})
  },
  methods: {
    init(stageIndex) {
      const {
        stem: {
          info: { audio = '' }
        }
      } = this.currentQuestion

      const stages = [
        {
          name: '播放题干',
          operateTips: '请再听一遍短文，完成转述',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_2_1.mp3'
        },
        {
          name: '播放对话',
          operateTips: '播放中',
          duration: audio
        },
        {
          name: '转述准备',
          operateTips: '下面，你有2分钟的时间做转述准备。转述的开头已给出',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_2_2.mp3'
        },
        {
          name: '空120秒',
          operateTips: '请阅题',
          duration: 120 * 1000,
          ignoreSpeed: true
        },
        {
          name: '准备录音',
          operateTips: '下面，请准备录音。听到提示音后，在2分钟内完成转述',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_3_2_3.mp3'
        },
        {
          beforeRunAction: () => {
            this.$refs.recorderRef.stop()
          },
          name: '开始录音',
          operateTips: '提示音',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/Di.mp3'
        },
        {
          beforeRunAction: () => {
            this.$refs.recorderRef.start()
          },
          name: '录音',
          operateTips: '录音中',
          duration: 120 * 1000,
          ignoreSpeed: true
        },
        {
          name: '停止录音',
          operateTips: '停止录音',
          duration: () => {
            return new Promise((resolve) => {
              const loading = this.$loading({
                lock: true,
                text: '保存录音...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.5)'
              })
              // 一分钟内上传不成功关闭loading弹窗
              const timer = setTimeout(() => {
                loading.close()
              }, 60000)
              const { localStudentAnswer } = this.currentQuestion
              const { examId, studentId, questionId, studentAnswer } = localStudentAnswer

              this.$refs.recorderRef.stop(async (res) => {
                const { data, file, format } = res

                const date = Date.now()
                const uploadPath = `exam/${examId}/${studentId}/${questionId}/0/0/${date}.${format}`
                const formData = new FormData()
                formData.append('file', file, `${date}.${format}`)
                formData.append('path', uploadPath)

                try {
                  const { data: answer } = await uploadFile(formData)
                  localStudentAnswer.studentAnswer = generateStudentAnswer({
                    anSqs: studentAnswer.anSqs,
                    anSqsIndex: 0,
                    ansIndex: 0,
                    answer
                  })
                  this.currentQuestion.localStudentAnswerStatus = 1
                  resolve()
                } catch (error) {
                  console.error(error)
                } finally {
                  clearTimeout(timer)
                  loading.close()
                }
              })
            })
          }
        }
      ]

      this.globalData.controller.reset()
      this.globalData.controller.init(stages, stageIndex)
    },
    handlerRecorderError({ message }) {
      this.$message.error(message)
    }
  }
}
</script>

<style lang="scss" scoped></style>
